package com.situ.springboot.controller;

import com.situ.springboot.annotation.MyLog;
import com.situ.springboot.pojo.User;
import com.situ.springboot.pojo.query.UserQuery;
import com.situ.springboot.service.IUserService;
import com.situ.springboot.util.PageResult;
import com.situ.springboot.util.Result;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @MyLog
    @RequestMapping("/selectByPage")
    public PageResult<User> selectByPage(UserQuery userQuery) {
        return userService.selectByPage(userQuery);
    }

    @MyLog
    @RequestMapping("/deleteById")
    public Result deleteById(String id) {
        userService.deleteById(Integer.parseInt(id));
        return Result.ok("删除成功");
    }

    @MyLog
    @RequestMapping("/deleteAll")
    public Result deleteAll(String[] ids) {
        userService.deleteAll(ids);
        return Result.ok("删除成功");
    }

    @MyLog
    @RequestMapping("/add")
    public Result add(User user) {
        userService.add(user);
        return Result.ok("添加成功");
    }

    @MyLog
    @RequestMapping("/selectById")
    public Result selectById(String id) {
        User user = userService.selectById(Integer.parseInt(id));
        return Result.ok(user);
    }

    @MyLog
    @RequestMapping("/update")
    public Result update(User user) {
        userService.update(user);
        return Result.ok("修改成功");
    }

    @MyLog
    @RequestMapping("/login")
    public Result login(String name, String password, HttpSession session) {
        User user = userService.login(name, password);
        if(user == null) {
            return Result.error("用户名或密码错误");
        }
        if(user.getStatus() == 0) {
            return Result.error("该用户已禁用");
        }
        session.setAttribute("user", user);
        return Result.ok("登录成功");
    }

    @MyLog
    @RequestMapping("/logout")
    public Result logout(HttpSession session) {
        session.removeAttribute("user");
        return Result.ok("退出成功");
    }
}
